﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace TaoPortal.Common.Utility
{
    #region Long，DateTime类型转换
    internal class MyConvert : Newtonsoft.Json.Converters.RegexConverter
    {
        public override bool CanConvert(Type objectType)
        {
            if (objectType.FullName.Contains("System.Int64") || objectType.FullName.Contains("System.DateTime"))
            {
                return true;
            }
            return false;
        }

        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            if (value.GetType().Name == "DateTime")
            {
                writer.WriteValue(((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss"));
            }
            else
            {
                writer.WriteValue(value.ToString());
            }
        }
    }
    #endregion

    /// <summary>
    /// JSON序列化
    /// </summary>
    public sealed class JsonSerialization
    {
        /// <summary>
        /// 将对象转换成JSON格式字符串
        /// </summary>
        /// <param name="obj">需要转的对象</param>
        /// <returns>JSON格式字符串</returns>
        public static string SerializeObject(object obj)
        {
            MyConvert MyConvert = new MyConvert();
            var str = Newtonsoft.Json.JsonConvert.SerializeObject(obj, MyConvert);

            return str;
        }
        /// <summary>
        /// 将对象字符串转换成对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="objStr">对象字符串</param>
        /// <returns>对象</returns>
        public static T DeserializeObject<T>(string objStr)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(objStr);
        }
    }
}
